//
//  OrderDetailVC.swift
//  NewDelivery
//
//  Created by 天下宅 on 2016/11/10.
//  Copyright © 2016年 天下宅. All rights reserved.
//

import UIKit
import SwiftyJSON
import SVProgressHUD
class OrderDetailVC: BaseVC,UIWebViewDelegate {

    
    var orderID:String?
    
//    var orderNumberLabel:UILabel!
//    var orderStatusLabel:UILabel!
//    var orderPayStatusLabel:UILabel!
//    var orderArrivaTimeLabel:UILabel!
//    var orderPriceLabel:UILabel!
    
    
    var shopPhoneLabel:UILabel!
    var shopAddressLabel:UILabel!
    var customerPhoneLabel:UILabel!
    var customerAddressLabel:UILabel!
    
    var remarkLabel:UILabel!
    
    var scrollView:UIScrollView!
    
    var handleBtn:UIButton!
    
    var webView:UIWebView = {
        return UIWebView.init()
    }()
    
    var thisDict:[String:JSON]!
    
    var status:String!//根据这个判断
    
    override func viewDidLoad() {
        super.viewDidLoad()

        
        let nav = WKNavView.creatNavView(WithTitle: "订单详情", vProtocol: self)
        self.view.addSubview(nav)
        nav.leftImage = UIImage.init(named: "左箭头")
        self.view.backgroundColor = UIColor.groupTableViewBackground
        
        
        scrollView = UIScrollView.init(frame: CGRect.init(x: 0, y: 64, width: screenWidth, height: screenHeight - 64))
        self.view.addSubview(scrollView)
        scrollView.backgroundColor = UIColor.groupTableViewBackground
        
        // Do any additional setup after loading the view.
        self.refreshInterFace()
    }
    
    func refreshInterFace()
    {
        if orderID != nil
        {
            NetWorkingManager.getOrderDetail(WithID: orderID!, hintStr: "获取数据中", block: {(state, data) in
                switch state
                {
                case .Faild(let msg):
                    self.view.wkMakeToastToCenter(message: msg)
                case .Success:
                    
                    for v in self.scrollView.subviews
                    {
                        v.removeFromSuperview()
                    }
                    
                    self.thisDict = data!.dictionaryValue
                    self.setInterFace()
                    print(data)
                }
            })
        }
    }
    
    func setInterFace()
    {
        let orderView = UIView.init(frame: CGRect.init(x: 0, y: 20, width: screenWidth, height: 250))
        orderView.backgroundColor = UIColor.white
        orderView.addLine(WithColor: UIColor.lightGray, model: [.top,.bottom])
        scrollView.addSubview(orderView)
        
        self.status = thisDict["status"]?.stringValue ?? "nil"
        
        let arr = ["订单编号：","订单状态：","是否支付：","配送时间：","总价："]
        
        let orderID = thisDict["dno"]?.stringValue ?? "nil"
        let orderStatus = thisDict["orderstatus"]?.stringValue ?? "nil" //待发货?
        let payStatus = thisDict["paystatusname"]?.stringValue ?? "nil"
        let postDate = thisDict["postdate"]?.stringValue ?? "nil"
        let total = thisDict["allcost"]?.stringValue ?? "nil"

        let contents = [orderID, orderStatus, payStatus, postDate, total]
        
        var lastView = orderView
        
        var index = 0
        for str in arr {
            let hintLabel = UILabel()
            hintLabel.font = UIFont.systemFont(ofSize: 16)
            orderView.addSubview(hintLabel)
            hintLabel.snp.makeConstraints({ (make) in
                make.left.equalToSuperview().offset(10)
                make.top.equalTo(lastView == orderView ? lastView : lastView.snp.bottom)
                make.height.equalTo(50)
                make.width.equalTo(110)
            })
            hintLabel.text = str
            lastView = hintLabel
            
            let contentLabel = UILabel()
            contentLabel.font = UIFont.systemFont(ofSize: 16)
            contentLabel.textColor = UIColor.lightGray
            orderView.addSubview(contentLabel)
            contentLabel.snp.makeConstraints({ (make) in
                make.left.equalTo(hintLabel.snp.right)
                make.right.equalToSuperview()
                make.top.bottom.equalTo(hintLabel)
            })
            contentLabel.text = contents[index]
            index += 1
        }
        
        let shopView = self.addInfoView(WithLastView: orderView, flag: true)
        let customerView = self.addInfoView(WithLastView: shopView, flag: false)
        let detailView = self.addDetailView(WithLastView: customerView)
        
        print(status)
        var title = "马蛋"
        var enable = true
        if status == "0"{
            //待抢订单
            title = "抢单"
        }
        else if status == "1" {
            //抢单成功，要取货
            title = "我已取货"
        }
        else if status == "2"
        {
            title = "我已送达"
        }
        else if status == "3"
        {
            title = "订单已完成"
            enable = false
        }
        else
        {
            title = "订单关闭"
            enable = false
        }
        handleBtn = UIButton.button(withTitle: title, bgColor: !enable ? UIColor.lightGray : MainGreenColor)
        handleBtn.frame = CGRect.init(x: 10, y: detailView.bottom + 20, width: screenWidth - 20, height: 50)

//        handleBtn.setTitleColor(UIColor.gray, for: UIControlState.disabled)
        scrollView.addSubview(handleBtn)
        handleBtn.addTarget(self, action: #selector(handle), for: .touchUpInside)
        handleBtn.isEnabled = enable
        handleBtn.layer.cornerRadius = 5
        scrollView.contentSize = CGSize.init(width: screenWidth, height: handleBtn.bottom + 20)
    }
    
    func addDetailView(WithLastView view:UIView) -> UIView {
        let detailView = UIView.init(frame: CGRect.init(x: 0, y: view.bottom + 20, width: screenWidth, height: 120))
        detailView.backgroundColor = UIColor.white
        detailView.addLine(WithColor: .lightGray, model: [.top,.bottom])
        scrollView.addSubview(detailView)
        
        let detailHintLabel = UILabel.init(frame: CGRect.init(x: 10, y: 0, width: screenWidth - 10, height: 40))
        detailHintLabel.text = "菜单详情"
        detailView.addSubview(detailHintLabel)
        detailHintLabel.addLine(WithColor: .lightGray, model: [.bottom])
        
        remarkLabel = UILabel.init(frame: .init(x: 10, y: detailHintLabel.bottom, width: detailHintLabel.width, height: 150))
        remarkLabel!.numberOfLines = 0
        remarkLabel!.textColor = UIColor.lightGray
        remarkLabel!.font = UIFont.systemFont(ofSize: 15)
        detailView.addSubview(remarkLabel!)
        remarkLabel.text = thisDict["content"]?.string ?? ""
        remarkLabel!.sizeToFit()
        
        var lastView:UIView = remarkLabel
        
        if let detArr = thisDict["det"]!.array
        {
            for data in detArr {
                if let dict = data.dictionary
                {
                    let gm = GoodsModel.init(WithDict: dict)
                    let gv = GoodsView.creatGoodsView(WithModel: gm)
                    gv.origin = CGPoint.init(x: 0, y: lastView.bottom)
                    lastView = gv
//                    gv.backgroundColor = UIColor.brown
                    detailView.addSubview(gv)
                }
            }
        }
        
        detailView.height = lastView.bottom
        return detailView
    }
    
    //true 商家 false 买家
    func addInfoView(WithLastView lastView:UIView, flag:Bool) -> UIView
    {
        let shopView = UIView.init(frame: CGRect.init(x: 0, y: lastView.bottom + 20, width: screenWidth, height: 150))
        shopView.addLine(WithColor: UIColor.lightGray, model: [.top,.bottom])
        scrollView.addSubview(shopView)
        shopView.backgroundColor = UIColor.white
        let shopHintLable = UILabel.init(frame: CGRect.init(x: 10, y: 0, width: screenWidth - 10, height: 40))
        shopHintLable.text = flag ? "商家信息" : ("买家信息  " + (thisDict["buyername"]?.string ?? ""))
        shopView.addSubview(shopHintLable)
        shopHintLable.addLine(WithColor: .lightGray, model: [.bottom])
        
        let button = UIButton.init(type: .custom)
        button.frame = CGRect.init(x: screenWidth - 100, y: shopHintLable.bottom + 5, width: 100, height: shopView.height - shopHintLable.bottom - 10)
        button.setImage(UIImage.init(named: "电话图标"), for: UIControlState.normal)
        shopView.addSubview(button)
        button.addLine(WithColor: .lightGray, model: [.left])
        button.addTarget(self, action: #selector(call(_:)), for: .touchUpInside)
        button.tag = 100 + (flag ? 1 : 0)
        
        var phoneLabel = flag ? shopPhoneLabel : customerPhoneLabel
        
        phoneLabel = UILabel.init(frame: CGRect.init(x: 10, y: shopHintLable.bottom, width: screenWidth - 10 - button.width, height: 40))
        phoneLabel!.textColor = UIColor.lightGray
        shopView.addSubview(phoneLabel!)
        phoneLabel!.text = flag ? ("商家电话：" + thisDict["shopphone"]!.stringValue ): ("买家电话：" + thisDict["buyerphone"]!.stringValue)
        
        
        
        let shopIV = UIImageView.init(frame: .init(x: 10, y: phoneLabel!.bottom, width: 10, height: 17))
        shopIV.image = UIImage.init(named: "定位")
        shopView.addSubview(shopIV)
        
        
        var addressLabel = flag ? shopAddressLabel : customerAddressLabel

        
        addressLabel = UILabel()
        addressLabel!.numberOfLines = 0
        addressLabel!.textColor = UIColor.lightGray
        addressLabel!.font = UIFont.systemFont(ofSize: 15)
        addressLabel!.text = flag ? thisDict["shopaddress"]!.stringValue : thisDict["buyeraddress"]!.stringValue
        
        addressLabel!.frame = CGRect.init(x: shopIV.right + 5, y: shopIV.top, width: screenWidth - shopIV.right - 5 - button.width, height: shopView.height - phoneLabel!.bottom)
        shopView.addSubview(addressLabel!)
        addressLabel!.sizeToFit()

        scrollView.addSubview(shopView)
        
        return shopView
    }

    func call(_ btn:UIButton) {

        var phone = ""
        if (btn.tag - 100) == 1
        {
            print("商家电话")
            phone = thisDict["shopphone"]!.stringValue
        }
        else
        {
            print("买家电话")
            phone = thisDict["buyerphone"]!.stringValue

        }
        
        let url = URL.init(string: "tel://" + phone)
        let urlR = URLRequest.init(url: url!)
//        self.webView.delegate = self//无法控制
        self.webView.loadRequest(urlR)

    }
    
//    func webViewDidStartLoad(_ webView: UIWebView) {
//        SVProgressHUD.show(withStatus: "请稍候")
//    }
//    
//    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
//        SVProgressHUD.dismiss()
//        self.view.makeToast("拨号失败，请重新重新尝试")
//    }
//    
//    func webViewDidFinishLoad(_ webView: UIWebView) {
//        print("完成")
//        SVProgressHUD.dismiss()
//    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func handle()
    {
        
        
        var dotType = ""
        if status == "0"{
            //待抢订单
            dotType = "joinorder"
        }
        else if status == "1" {
            //抢单成功，要取货
            dotType = "pickorder"
        }
        else if status == "2"
        {
            dotType = "sendorder"
        }
//        else if status == "3"
//        {
//            dotType = "overorder"
//        }
        
        if dotType.characters.count == 0
        {
          self.view.wkMakeToastToCenter(message: "此订单不可操作,请联系技术人员询问")
        }
        print(status)
        print(dotType)
        
        NetWorkingManager.handleOrder(WithID: orderID!, dotType: dotType,hintStr:nil, block: {(state, data) in
            switch state
            {
            case .Faild(let msg):
                self.view.wkMakeToastToCenter(message: msg)
            case .Success:
                print("成功")
                self.refreshInterFace()
            }
        })
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
